package backed.service.impl;

import backed.entity.SecondHandItem;
import backed.repository.SecondHandItemRepository;
import backed.service.SecondHandItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class SecondHandItemImpl implements SecondHandItemService {

    @Autowired
    private SecondHandItemRepository secondHandItemRepository;

    @Override
    public SecondHandItem publish(Long userId, String title, String description, 
                                 Double price, String conditionLevel, String category, 
                                 String images) {

        SecondHandItem item = new SecondHandItem();

        
        // 设置必要字段
        item.setUserId(userId);
        item.setTitle(title);
        item.setPrice(BigDecimal.valueOf(price));
        
        // 设置可选字段（可为空）
        item.setDescription(description);
        item.setConditionLevel(conditionLevel);
        item.setCategory(category);
        item.setImages(images);
        
        // 设置默认值
        item.setStatus("on_sale");
        item.setViewCount(0);

        return secondHandItemRepository.save(item);
    }


    @Override
    public List<SecondHandItem> getUserItems(Long userId) {
        return secondHandItemRepository.findByUserId(userId);
    }

    @Override
    public List<SecondHandItem> getUserItemsByStatus(Long userId, String status) {
        return secondHandItemRepository.findByUserIdAndStatus(userId, status);
    }
    
    @Override
    public Page<SecondHandItem> getItemsList(String category, String keyword, int page, int size) {
        // 创建分页请求，按id倒序排序
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "id"));
        
        // 执行数据库查询
        Page<SecondHandItem> itemsPage = category != null && !category.isEmpty() 
            ? secondHandItemRepository.findByStatusAndCategory("on_sale", category, pageable)
            : secondHandItemRepository.findByStatus("on_sale", pageable);
        
        // 关键词过滤处理
        if (keyword != null && !keyword.isEmpty()) {
            List<SecondHandItem> filteredItems = itemsPage.getContent().stream()
                    .filter(item -> (item.getTitle() != null && item.getTitle().contains(keyword)) ||
                                    (item.getDescription() != null && item.getDescription().contains(keyword)))
                    .collect(java.util.stream.Collectors.toList());
            
            return new PageImpl<>(filteredItems, pageable, filteredItems.size());
        }
        
        return itemsPage;
    }

    @Override
    public SecondHandItem getItemInfo(Long id) {
        return secondHandItemRepository.findById(id).orElse(null);
    }

    @Override
    public SecondHandItem update(SecondHandItem item) {
        return secondHandItemRepository.save(item);
    }
    
    @Override
    public boolean deleteItem(Long id) {
        SecondHandItem item = secondHandItemRepository.findById(id).orElse(null);
        if (item != null) {
            // 软删除：将状态设置为removed
            item.setStatus("removed");
            secondHandItemRepository.save(item);
            return true;
        }
        return false;
    }


}
